const User = require("../model/user.model");
// 雪花id生成
const SNOWFLAKE = require("@zsea/snowflake");
const snowflake = new SNOWFLAKE({
  type: "string",
});

class UserService {
  async createUser(username, password, phone) {
    try {
      const res = await User.create({
        app_user_id: snowflake.nextId(),
        username: username,
        password: password,
        phone: phone,
      });
      if (res.dataValues) {
        delete res.dataValues.pwd;
        return {
          code: "10000",
          message: "注册成功",
          data: res.dataValues,
        };
      }
    } catch (error) {
      console.log(error);
    }
  }
  // 校验用户是否存在
  async checkUserDoesExsit(username) {
    const findOption = {};
    try {
      if (username) {
        Object.assign(findOption, { username });
      }
      const res = await User.findOne({
        raw: true,
        where: findOption,
      });
      return res ? res : null;
    } catch (error) {}
  }
  // 检查用户登录
  async checkUserLogin(username, pwd) {
    const findOption = {};
    try {
      if (username) {
        Object.assign(findOption, { username });
      }
      const res = await User.findOne({
        raw: true,
        where: findOption,
      });
      delete res.password;
      return res;
    } catch (error) {
      console.log(error);
    }
  }
  // 更改密码
  async changePwd(id, pwd) {
    const findOption = {};
    if (id) {
      Object.assign(findOption, { id });
    }
    const res = await User.update(
      { pwd },
      {
        where: findOption,
      }
    );
    return res[0] > 0 ? true : false;
  }
}

module.exports = new UserService();
